package thread.communicate.tradition.communication;

/**
 *
 * aim:
 * 子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着再回到主线程又循环100次,以此类推,如此循环50次.
 * Created by 4790K_NSL on 2017/4/18.
 * 注意的地方:
 * Business 类:
 * 把需要同步协调的代码放入不同的方法中,再使用不同的线程去运行.
 */
public class OneByOne {
    static public void main(String[] args){
        OneByOne oneByOne=new OneByOne();
        oneByOne.test();

    }

    public  void test(){
        final  Business business=new Business();

        new Thread(){
            public void run(){
                for(int i=1;i<=50;i++){
                    business.main(i);
                }
            }
        }.start();

        new Thread(){
            public void run(){
                for(int i=1;i<=50;i++){
                    business.sub(i);
                }
            }
        }.start();

    }

    class Business{
        int signal=1;
        public synchronized  void main(int j){
            while(signal!=0){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for(int i=1;i<=100;i++){
                System.out.println("j=" + j + " i="+i+" : main is running.");
            }
            signal=1;
           // this.notify();
        }

        public synchronized void sub(int j){
            while(signal!=1){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for(int i=1;i<=10;i++){
                System.out.println("j=" + j + " i="+i+" : sub is running.");
            }
            signal=0;
            this.notify();
        }
    }


}
